<?php

namespace common\models;

use Yii;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use Helper;

class SmsBatchLog extends ActiveRecord
{

    public $country;
    public $signid;
    public $total;

    private $limitTop = 100;

    const SCENARIO_BATCH_SEND = 'batch_send';

    public static function tableName()
    {
        return '{{%sms_batch_log}}';
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['addtime'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['uptime']
                ]
            ],

        ];
    }

    public function rules()
    {
        return [
            ['appkey', 'required', 'on' => [self::SCENARIO_BATCH_SEND], 'message' => Yii::t('code', '1001')],
            ['country', 'required', 'on' => [self::SCENARIO_BATCH_SEND], 'message' => Yii::t('code', '1002')],
            ['country', 'checkCountry', 'skipOnError' => false, 'skipOnEmpty' => false, 'on' => [self::SCENARIO_BATCH_SEND]],
            ['data', 'required', 'on' => [self::SCENARIO_BATCH_SEND], 'message' => Yii::t('code', '1003')],
            ['data', 'checkMobileNum', 'on' => [self::SCENARIO_BATCH_SEND]],
            ['tplid', 'required', 'on' => [self::SCENARIO_BATCH_SEND], 'message' => Yii::t('code', '1006')],
            ['signid', 'required', 'on' => [self::SCENARIO_BATCH_SEND], 'message' => Yii::t('code', '1007')],
            ['content', 'required', 'on' => [self::SCENARIO_BATCH_SEND], 'message' => Yii::t('code', '1008')],
            ['gid', 'required', 'on' => [self::SCENARIO_BATCH_SEND], 'message' => Yii::t('code', '1024')],
            ['codetype', 'default', 'value' => -1],
            ['codetype', 'string', 'length' => [1, 25], 'message' => Yii::t('code', '1009')],
            [['code', 'tplid', 'statu', 'total'], 'integer'],
            [['vparam1', 'vparam2', 'vparam3', 'ip', 'sendtype', 'content', 'uptime', 'appkey', 'data'], 'default', 'value' => null],
            [['provider', 'uptime', "mdata", 'addtime'], 'safe'],

        ];
    }

    public function checkCountry($attribute, $params)
    {
        $countrys = require(Yii::getAlias('@common/data/country.php'));
        if ((!isset($countrys[$this->country]) || empty($countrys[$this->country]))) {
            $name = array_search($this->country, array_column($countrys, 'code', 'sname'));
            if ($name === false) {
                $this->addError($attribute, Yii::t('code', '1005'));
            }
        }
    }

    public function checkMobileNum($attribute, $params)
    {
        $mobiles = explode(',', $this->data);
        if (count($mobiles) > $this->limitTop) {
            $this->addError($attribute, Yii::t('code', '1057', ['limit' => $this->limitTop]));
        }
    }

}

?>